import { useI18n } from "vue-i18n";
import useApiPromiseHandler from "./api-promise-handler";
import { ref } from "vue";
import { api } from "@/global/utils/api";

export default function useFindReply(replyList, targetUrl) {

  const { t } = useI18n();
  const currentPage = ref(1);
  const PAGESIZE = 5;
  const isFetchingList = ref(false);
  const noMore = ref(false);


  const findReply = (page, countPerPage, targetId, onSuccessed, onFaild) => {
    useApiPromiseHandler(t,
      api.get(`${targetUrl}/findAll/${targetId}/${page}/${countPerPage}`),
      onSuccessed, onFaild,
      () => isFetchingList.value = false
    )
  };

  const fetch = (targetId) => {
    if (noMore.value) return;
    isFetchingList.value = true;
    findReply(currentPage.value, PAGESIZE, targetId, (resp) => {
      resp.data.content.forEach(reply => {
        replyList.value.push(reply);
      });
      if (!resp.data.last)
        currentPage.value++;
      else 
        noMore.value = true;
    }, (err) => console.log(err));
  };


  return { fetch, currentPage, isFetchingList, noMore };

}